const express=require('express');
const mysql=require('mysql');
const urlobj=require('url');
//引用自定义
const commte=require('../../libs/common.js');
//链接数据库
var db=mysql.createPool({
    host:'localhost',
    user:'root',
    password:'',
    database:'leasedb'
});
//业务逻辑
module.exports = function() {
    var router = express.Router();
   //开始渲染后台首页
    router.get('/AddPrimaryClassification.html',function(req,res){
        res.render("admin/AddPrimaryClassification.ejs");
    });
    router.use('/AddPrimaryClassification.html',function(req,res){

        //判断是否登陆
        if(req.session['userId']==null||req.session['userId']=="")
        {
            res.status(400).send('<script>alert("请登录");window.location.href="login.html";</script>').end();
        }

        if(req.body.shrpitname==""||req.body.shrpitname==null)
        {
            res.status(400).send('<script>alert("请输入商品分类名称");window.location.href="AddPrimaryClassification.html";</script>').end();
            return false;
        }

        db.query("SELECT * FROM `classa` WHERE classAName='"+req.body.shrpitname+"'",function(err,data){
        //查询当前添加的一级分类是否添加过
            if(err)
            {
                res.status(400).send('<script>alert("操作失败");</script>').end();
            }
            if(data)
            {
                var cont=data.length;

                if(cont>0)
                {

                    res.status(400).send('<script>alert("存在该分类");window.location.reload();</script>').end();

                }else if(cont==0)
                {
                    db.query("INSERT INTO `classa`(`classAId`, `classAName`, `classAtime`) VALUES (0,'"+req.body.shrpitname+"','"+commte.getTime()+"')",function (err,data) {
                        if(err)
                        {
                            res.status(400).send('<script>alert("添加失败");</script>').end();
                        }
                        if(data)
                        {
                            res.status(400).send('<script>alert("添加成功");window.location.href="PrimaryClassification.html";</script>').end();
                        }
                    })
                }
            }
        });
    });
    return router;
}